<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="!visible" :span="12">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="130" />
          </el-form-item>
        </el-col>
        <el-col v-if="isDealName" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :scope-authority="true"
              parameters="deal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal">
              <el-radio-button
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项名称')" prop="itemName">
            <el-input v-model="form.itemName" maxlength="125" show-word-limit :placeholder="$t('事项名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="happenTime">
            <DatePicker v-model="form.happenTime" :placeholder="$t('发生时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项类别')" prop="itemType">
            <el-select v-model="form.itemType" filterable :placeholder="$t('事项类别')">
              <el-option
                v-for="dict in itemTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('用印份数')">
            <el-input-number v-model="form.fileCount" :min="0" :max="9999" :placeholder="$t('用印份数')" />
          </el-form-item>
        </el-col>
        <el-col :span="!isShow ? 24 : 12">
          <el-form-item :label="$t('是否处理')">
            <el-radio-group v-model="form.handle" @change="handleChange">
              <el-radio-button
                v-for="dict in handleOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="isShow" :span="12">
          <el-form-item :label="$t('处理日期')" prop="handleTime">
            <DatePicker v-model="form.handleTime" :placeholder="$t('处理日期')" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShow" :span="12">
          <el-form-item :label="$t('处理方式')" prop="handleMode">
            <el-input v-model="form.handleMode" maxlength="125" show-word-limit :placeholder="$t('处理方式')" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShow" :span="24">
          <el-form-item :label="$t('处理描述')" prop="handleDesc">
            <el-input v-model="form.handleDesc" type="textarea" maxlength="2000" :autosize="{ minRows: 8 }" show-word-limit :placeholder="$t('处理描述')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('事项描述')" prop="itemDesc">
            <el-input v-model="form.itemDesc" type="textarea" maxlength="2000" :autosize="{ minRows: 8 }" show-word-limit :placeholder="$t('事项描述')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--用印明细-->
      <div v-if="form.isSeal === 'Y'" style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table :data="form.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center" min-width="350">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                  @change="duplicateVerificationSubject"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')" align="center" min-width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeDict"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" min-width="300">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input v-model="scope.row.remark" type="textarea" :autosize="{ maxRows: 5 }" :maxlength="2000" show-word-limit :placeholder="$t('备注')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="(!otherBtnHide && !btnMeetingHide) || !useProcess" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:matters:remove']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="(!otherBtnHide && !btnMeetingHide) || !useProcess" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <FileTable :list.sync="form.fileList" data-type="deal_matters" has-permi="deal:matters" :business-id="autoBusinessId($route.query.id ? $route.query.id : form.dealId, form)" :btn-show="(!otherBtnHide && !btnMeetingHide) || !useProcess" />
    </el-form>
    <div v-if="meetingToSaveBtn" slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button v-if="refType === 'meeting'" @click="$parent.$parent.formOpen = false">{{ $t('取消') }}</el-button>
      <el-button v-if="(refType === 'meeting' && !btnMeetingHide) && useProcess" has-permi="deal:meeting" type="primary" @click="confirmHandle">{{ $t('确认') }}</el-button>
      <el-button v-if="refType === 'meeting' && !useProcess" has-permi="deal:meeting" type="primary" @click="confirmHandle">{{ $t('确认') }}</el-button>
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="refType !== 'meeting' && useProcess" ref="formBtn" :bus-data="form" :btn-hide="btnHide" has-permi="deal:matters" :menu-key="menuKey" />
      <!--未使用流程：保存 取消按钮-->
      <save-btn v-else-if="refType !== 'meeting' && !useProcess" has-permi="deal:matters" :btn-hide="btnHide" />
    </div>
  </div>
</template>

<script>
    import { saveDealMatters, getDealMatters } from '@/api/deal/matters/dealMatters'
    import { getDealName } from '@/api/base/deal/dealBase'
    import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import MainBodySelect from '@/components/MainBodySelect'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    export default {
      components: {
        MainBodySelect
      },
      props: {
        visible: {
          type: Boolean,
          default: false
        },
        refType: {
          type: String,
          default: '',
          desc: '引用类型'
        },
        btnMeetingHide: {
          type: Boolean,
          default: false
        }
      },
        data() {
            return {
                // 菜单标识
                menuKey: 'deal_matters',
                useProcess: false,
                // 事项类别 字典deal_matters_category字典
                itemTypeOptions: [], // 是否处理 字典sys_yes_no字典
                handleOptions: [], // 表单参数
                // 是否用印
                isSealOptions: [],
                // 用印类型
                sealTypeDict: [],
                form: {
                  oaSealDetailList: [],
                  fileList: []
                },
                isShow: false,
                // 是否隐藏保存按钮
                btnHide: false,
                // 三会中打开并且流程结束,当前不能编辑
                meetingToSaveBtn: true,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单校验
                rules: {
                  itemName: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ], happenTime: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ], itemType: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  handleTime: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ], actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], isSeal: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], dealId: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  sealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否展示项目名称
                isDealName: this.$attrs.parameter && this.$attrs.parameter.quick && this.$attrs.parameter.quick === 'true',
                // 是否只读
                isDealEdit: false
            }
        },
        created() {
          this.getUseProcess()
            this.getDicts('deal_matters_category').then(response => {
                this.itemTypeOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
                this.handleOptions = response.data
                this.isSealOptions = response.data
            })
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined && data.id !== '' && data.id !== null) {
                    getDealMatters(data.id).then(response => {
                        this.form = response.data
                        this.handleChange(this.form.handle)
                      if (data.actStatus === 'W' || data.actStatus === 'D') {
                        this.btnMeetingHide = true
                      }
                      this.loading = false
                    })
                } else {
                    if (this.refType === 'meeting' && data) {
                      this.form = data
                    } else {
                      this.reset()
                    }
                    // 默认带出流程中必须要传的附件
                    if (data) {
                      this.form.fileList = data.fileList
                    }
                    this.handleChange(this.form.handle)
                  this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                dealId: this.$route.query.id,
                companyId: this.$route.query.companyId,
                itemName: undefined,
                happenTime: undefined,
                itemType: undefined,
                handle: 'N',
                handleTime: undefined,
                handleMode: undefined,
                handleDesc: undefined,
                itemDesc: undefined,
                isSeal: 'N',
                oaSealDetailList: [],
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                actId: undefined,
                actStatus: undefined,
                fileCount: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm(type) {
                // 关闭form页面遮罩层
                this.loading = false
                if (type !== 'actSave') {
                  // 关闭form页面
                  if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                  }
                  // 刷新list页面
                  if (this.$parent.$parent.getList !== undefined) {
                    this.$parent.$parent.getList()
                  }
                }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  let flag = true
                  if (this.form.isSeal === 'Y') {
                    if (this.form.oaSealDetailList.length === 0) {
                      this.msgError(this.$t('至少添加一条用印明细!'))
                      flag = false
                    }
                  }
                  // 验证数据
                  if (valid && flag) {
                    // 弹出遮罩层
                    this.loading = true
                    // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
                    this.form.saveType = type
                    this.form.useProcess = this.useProcess
                    // 新增数据时，不使用流程直接改为审批完成
                    if (!this.useProcess && !this.form.id) {
                      this.form.actStatus = 'W'
                    }
                    // 保存数据
                    saveDealMatters(this.form).then(response => {
                      if (response.code === 200) {
                        // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                        this.form.id = response.data.id
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 启动流程
                          this.startProcess(response.data.id)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm(type)
                        }
                        resolve(response.data.id)
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject(response)
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                    reject()
                  }
                })
              })
           },
            // 启动流程
           startProcess: async function(dataId) {
             var dealName = await getDealName(this.$route.query.id ? this.$route.query.id : this.form.dealId)
             this.loading = false
             // 启动流程时候传入的参数
             const processData = {}
             // 待办标题
             processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
             // 业务表名
             processData.dataTable = 'deal_matters'
             // 业务ID
             processData.dataId = dataId
             // 业务表单地址(待办页面需要打开的页面)
             processData.formPath = '@/views/deal/matters/dealMattersForm'
             processData.viewPath = '@/views/deal/matters/dealMattersView'
             // 菜单标识(根据菜单标识判断的走哪个流程)
             processData.menuKey = this.menuKey
             this.startProcessByMenu(processData, () => {
               this.form.actStatus = 'D'
               this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
               this.closeForm()
             })
           },
          handleChange(value) {
            // eslint-disable-next-line no-empty
            if (value === 'Y') {
              this.isShow = true
            } else {
              this.isShow = false
              this.form.handleTime = undefined
              this.form.handleMode = undefined
              this.form.handleDesc = undefined
            }
          },
          confirmHandle() {
            this.$refs['form'].validate(valid => {
              let flag = true
              if (this.form.isSeal === 'Y') {
                if (this.form.oaSealDetailList.length === 0) {
                  this.msgError(this.$t('至少添加一条用印明细!'))
                  flag = false
                }
              }
              if (this.isDealEdit && !this.form.dealId) {
                this.msgError(this.$t('请先在三会选择项目名称!'))
                flag = false
              }
              if (valid && flag) {
                this.$parent.$parent.formOpen = false
                this.$emit('meeting', this.form)
              }
            })
          },
          // 用印明细
          addPayment() {
            const row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (!(this.form.oaSealDetailList instanceof Array)) {
              this.$set(this.form, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealDetailList.push(row)
            })
          },
          // 删除用印明细
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteOaSealDetail(id)
                }).then(() => {
                this.form.oaSealDetailList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealDetailList.splice(index, 1)
            }
          },
          // 用印主体校验重复
          duplicateVerificationSubject(val) {
            this.$nextTick(() => {
              if (this.form.oaSealDetailList !== undefined && this.form.oaSealDetailList !== null) {
                var count = 0
                this.form.oaSealDetailList.some((item, index) => {
                  if (item.investMain === val) {
                    if (count > 0) {
                      this.form.oaSealDetailList.splice(index, 1)
                      this.msgError(this.$t('该主体已存在'))
                      return true
                    }
                    count++
                  }
                })
              }
            })
          },
          // 获取是否使用流程
          getUseProcess() {
            getMenuProcess('deal_matters').then(response => {
              this.useProcess = !!response.data
            })
          },
          // 快捷入口添加时获取公司id
          changeDeal(item) {
              console.log(item)
          }
        }
    }
</script>
